package com.ming.springboot.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * Created by mqsi on 2022/5/24 14:59
 */
@Component
public class SelfAuthenticationProvider implements AuthenticationProvider {
	@Autowired
	SelfUserDetailService selfUserDetailService;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		String username = (String) authentication.getPrincipal();
		String password = (String) authentication.getCredentials();
		UserDetails userDetails = selfUserDetailService.loadUserByUsername(username);
		if (!password.equals(userDetails.getPassword())){
			throw new BadCredentialsException("用户名或密码不正确，请重新登录！");
		}
		// 此处可以直接传入userDetails参数（之前传入了username）
		return new UsernamePasswordAuthenticationToken(userDetails, password, authentication.getAuthorities());
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return true;
	}
}
